/* eslint-disable no-dupe-keys */
<template>
  <div class="me_search">
    <el-dialog
      title="添加人员"
      :visible.sync="SearchUserListData.dialogVisible"
      class="small"
      height="50%"
      :before-close="handleClose"
      :modal-append-to-body="false"
    >
      <div class="box">
        <div class="left">
          <div class="left-top">
            <div class="inputDeep">
              <el-autocomplete
                v-model="input"
                :fetch-suggestions="querySearchAsync"
                placeholder="搜索名字"
                @select="handleSelect"
              />
            </div>
            <div class="button">
              <!-- closable -->
              <el-tag
                v-for="(tag, index) in tableDataList"
                :key="index"
                :disable-transitions="false"
                class="tag"
                closable
                @close="handleCloses(tag)"
              >
                {{ tag.label }}
              </el-tag>
            </div>
          </div>
          <div class="left-but">
            <el-button type="primary" @click="confirm"> 确 定 </el-button>
            <el-button @click="SearchUserListData.dialogVisible = false">
              取 消
            </el-button>
          </div>
        </div>
        <div class="right">
          <div>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item
                v-for="(item, index) in breadcrumb"
                :key="item.id"
                ><span @click="goTo(item.id, index)">{{
                  item.label
                }}</span></el-breadcrumb-item
              >
            </el-breadcrumb>
            <el-table
              ref="tableData"
              height="35vh"
              :data="tableData"
              style="width: 100%"
              :show-header="false"
              :select-on-indeterminate="true"
              :row-key="getRowKeys"
              @cell-click="click"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="selection"
                width="55"
                :reserve-selection="true"
                :selectable="checkboxT"
              />
              <el-table-column prop="label" />
            </el-table>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" />
    </el-dialog>
  </div>
</template>

<script>
import '@/styles/search.scss'
import { getsearch } from '@/api/uc/search'
import { arrDifferent, appendIsSelection, expandArr } from '@/utils/common'
import { searchUserByKeyword } from '@/api/uc/user.js'

export default {
  components: {},
  props: ['SearchUserListData'],
  data() {
    return {
      dialogVisible: false,
      groupUserTree: [],
      roleUserTree: [],
      tableData: [],
      dataList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      permissionIds: [],
      input: '',
      breadcrumb: [],
      terrData: [],
      checkedGh: [],
      restaurants: [],
      timeout: null,
      echoData: '',
      teamUserTree: [],
      tableDataList: [],
      searchList: [],
      i: 0,
      newArr: [],
      groupUserList: [],
      expand_tableData: [],
      listenStatus: ''
    }
  },
  computed: {},
  watch: {
    // tableData(data) {
    //   this.getItem(data)
    // },
    tableData: {
      handler(val) {
        this.getItem(val)
      },
      deep: true
    },
    tableDataList(data) {
      arrDifferent(data)
    },
    listenStatus: {
      handler(val) {
        this.setSelection(this.tableData)
      },
      deep: true
    }
  },
  mounted() {
    this.getSearch()
  },
  methods: {
    handleClose(done) {
      this.dataList = ''
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    //
    // 搜索
    querySearchAsync(queryString, cb) {
      var restaurants = this.expand_tableData
      var results = queryString
        ? this.createStateFilter(queryString)
        : restaurants
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        searchUserByKeyword({
          pageIndex: 0,
          pageSize: 1,
          userName: queryString
        }).then((res) => {
          res.data.forEach((item) => {
            item.value = item.userName
          })
          cb(res.data)
        })
      }, 1000 * Math.random())
    },
    createStateFilter(queryString) {
      const data = []
      this.expand_tableData.forEach((item) => {
        if (item.label.indexOf(queryString) === 0 && item.person != false) {
          item.value = item.label
          data.push(item)
        }
      })
      return data
    },
    // 搜索点击列表
    handleSelect(item) {
      this.input = ''
      this.setSelectionStatus(this.tableData, item.id, true)
      const data = {
        id: item.userId,
        label: item.userName
      }
      this.searchList.push(data)
      this.tableDataList = [...this.searchList, ...this.dataList]
    },
    // 获取数据
    async getSearch() {
      const getTableData = await getsearch()
      this.tableData = getTableData.data.groupUserTree[0].children
      this.expand_tableData = expandArr(this.tableData)
      this.terrData = Array.from(getTableData.data.groupUserTree[0].children)
      this.breadcrumb.push(getTableData.data.groupUserTree[0])
      appendIsSelection(this.tableData)
    },
    // tag回调
    handleCloses(tag) {
      this.listenStatus = Math.floor(Math.random() * 10000)
      this.tableDataList.splice(this.tableDataList.indexOf(tag), 1)
      this.setSelectionStatus(this.tableData, tag.id, false)
    },

    // 点击列表
    click(row) {
      if (row.children) {
        this.tableData = row.children
        this.breadcrumb.push({ label: row.label, id: row.id })
      }
    },

    checkboxT(row) {
      if (row.person == true) {
        return true
      } else {
        return false
      }
    },
    // 点击选择
    handleSelectionChange(sel, row) {
      this.dataList = sel
      this.tableDataList = [...this.searchList, ...this.dataList]
    },
    goTo(id, index) {
      const idl = id
      this.onId(idl, this.terrData)
      var flag = true
      for (var i = this.breadcrumb.length - 1; i >= 0; i--) {
        if (this.breadcrumb[i].id === idl) {
          flag = false
        }
        if (flag) {
          this.breadcrumb.splice(i, 1)
        }
      }
    },
    // 递归树
    onId(id, data) {
      for (const dat in data) {
        const e = data[dat]
        if (e.id === id) {
          this.tableData = e.children
          return
        } else if (id === this.breadcrumb[0].id) {
          this.tableData = this.terrData
        }
        if (e.children) {
          this.onId(id, e.children)
        }
      }
    },

    // 递归树
    getItem(data) {
      const newData = data || []
      newData.forEach((item) => {
        this.i++
        item.keys = this.i
        if (item.children) {
          this.getItem(item.children)
        } else {
          if (item.isSelection) {
            this.tableDataList.push(item)
            this.$refs.tableData.toggleRowSelection(item, true)
          }
        }
      })
    },
    setSelection(data) {
      const newData = data || []
      newData.forEach((item) => {
        if (item.children) {
          this.setSelection(item.children)
        } else {
          if (item.isSelection) {
            this.tableDataList.push(item)
            this.$refs.tableData.toggleRowSelection(item, true)
          } else {
            this.$refs.tableData.toggleRowSelection(item, false)
          }
        }
      })
    },
    confirm() {
      this.SearchUserListData.dialogVisible = false
      this.$emit('SearchUserList', this.tableDataList)
    },
    getRowKeys(row) {
      return row.keys
    },
    setSelectionStatus(data, id, isStatus) {
      const newData = data || []
      newData.forEach((e) => {
        if (e.children) {
          this.setSelectionStatus(e.children, id, isStatus)
        } else {
          if (e.id === id) {
            this.listenStatus = Math.floor(Math.random() * 10000)
            e.isSelection = isStatus
          }
        }
      })
      return newData
    }
  }
}
</script>

<style scoped>
</style>
